/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.glide;

import com.example.glide.slice.*;
import com.example.glide.utils.LogUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.bundle.IBundleManager;
import ohos.data.resultset.ResultSet;
import ohos.media.photokit.metadata.AVStorage;
import ohos.security.SystemPermission;
import ohos.utils.net.Uri;
import org.jetbrains.annotations.NotNull;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class MainAbility extends Ability {
    private static String TAG ="Glide";
    private ArrayList<String> data = new ArrayList<>();
    private DataAbilityHelper helper ;
    private Context classcontext;

    @Override
    public void onStart(Intent intent) {
        MyApplication.register(this, "MainAbility");
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        classcontext = getContext();
        //connectService();  //Note: If need media store then only call this connect service
    }


    private void connectService() {
        if (verifySelfPermission(SystemPermission.READ_USER_STORAGE) == IBundleManager.PERMISSION_GRANTED) {

            LogUtil.info(TAG, "permission granted");
        } else {
            requestPermissionsFromUser(new String[] {SystemPermission.READ_USER_STORAGE}, 0);
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || permissions.length == 0 || grantResults == null || grantResults.length == 0) {
            return;
        }
        if (requestCode == 0) {
            if (grantResults[0] == IBundleManager.PERMISSION_DENIED) {
                terminateAbility();
            } else {
                LogUtil.info(TAG, "permission granted");
                queryimages(classcontext);
            }
        }
    }

    public void queryimages(@NotNull Context abilitySlice) {
        // mSlice = (AbilitySlice) abilitySlice;
        helper = DataAbilityHelper.creator(abilitySlice);
        ResultSet resultSet = null;
        try {
            resultSet = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,new String[]{AVStorage.Images.Media.ID}, null);
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        if (resultSet == null) {
            return;
        }
        while (resultSet.goToNextRow()) {
            // data.add(String.valueOf(resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.Images.Media.ID))));
            data.add(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI + "/" + String.valueOf(resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.Video.Media.ID))));
        }
        resultSet.close();
        for (int i=0;i<data.size();i++) {
            Uri uri = Uri.parse(data.get(i));
            try {
                FileDescriptor fd =helper.openFile(uri, "r");
                FileInputStream fileInputStream = new FileInputStream(fd);

                if(null == fileInputStream)
                    LogUtil.info(TAG, "fileInputStream is null");

            } catch (DataAbilityRemoteException e) {
               e.printStackTrace();
            } catch (FileNotFoundException e) {
               e.printStackTrace();
            }

        }
    }
}
